//基础设施
var vm = new Vue({
    el: '#app',
    data: function() {
        return {
            index: 0,
            dateTime: '',
            locations: '',
            imgList: [],
            chosePeoples: [],
            content: '',
            peoples: [],
            isPublic: JSON.parse(GetQueryString('isPublic')) || false,
            pid: GetQueryString('pid') || 0,
            lng:0,
            lat:0
        }
    },
    mounted: function() {
        var that = this;
        mui.init({});
        mui.ready(function() {
            if(!that.pid){
                $.ajax({
                    type: 'post',
                    async: false,
                    url: '/getJsTicket',
                    data: {url: location.href.split('#')[0]},
                    success: function (data) {
                        wx.config({
                            debug: false,
                            appId: data.appId,
                            timestamp: data.timestamp,
                            nonceStr: data.noncestr,
                            signature: data.signature,
                            jsApiList: [
                                "getLocation"
                            ]
                        });
                        that.getLocation();
                        wx.error(function (res) {
                            alert(JSON.stringify(res));
                        });
                    }
                });
            }
            mui('.mui-scroll-wrapper').scroll({
                deceleration: 0.0005 //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
            });
            //人员选择
            $('.confirm-people').on('click', function() {
                $('#chosePeople').hide();
            })
            //获取时间
            var now = that.getTime();
            that.dateTime = now;
            that.locations = "";
            mui.previewImage();
            $(document.body).on('tap', 'img[data-preview-src]', function() {
                $('.showImgInfo').show();
            });
            $(document.body).on('tap', '#__MUI_PREVIEWIMAGE', function() {
                $('.showImgInfo').hide();
                return false;
            });
            that.getUserList(); //获取人员列表
        })
    },
    methods: {
        getLocation: function () {
            var that = this;
            wx.ready(function () {
                wx.getLocation({
                    type: 'wgs84',
                    success: function (res) {
                        that.getBaiduInfo(res.latitude, res.longitude);
                    }
                });
            });
        },
        getBaiduInfo: function (latit, longit) {
            var that = this;
            $.get("/getBaiduAddressInfo", {'latitude': longit, 'longitude': latit}, function (data) {
                if (data.status == '201') {
                    var address = data.address;
                    that.lng=data.lng;
                    that.lat=data.lat;
                    that.locations = address;
                }
            });
        },
        //获取人员列表
        getUserList: function() {
            var that = this;
            var list = [];
            $.getJSON('/getEventUsers', {}, function(res) {
                that.peoples = res
            })
        },
        showPeople: function() {
            $('#chosePeople').show();
        },
        chosed: function() {
            var that = this;
            var list = [];
            var lists = $('#chosePeople').find('input[name="people"]:checked');
            $.each(lists, function(i, item) {
                list.push({
                    "id": $(item).data("id"),
                    "name": $(item).data("name")
                })
            });
            that.chosePeoples = list;
        },
        upload: function(e) {
            var that = this;
            lrz(e.target.files[0], {
                //**width:最大宽度，quality:压缩比例，默认0.7**
                width: 1000
            })
                .then(function(rst) {
                    loading.show();
                    $.post('/upload_img', {
                        "imgData": rst.base64.replace(/^data:image\/(jpeg|png|gif);base64,/, '')
                    }, function(res) {
                        that.imgList.push({
                            "id": that.index,
                            "src": res
                        })
                        loading.hide();
                    })

                });
        },
        removeImg: function(index) {
            var that = this;
            mui.confirm('确认删除该照片？', '提示', ['取消', '确定'], function(val) {
                if (val.index == 1) {
                    that.imgList.splice(index, 1);
                }
            })
            return false;
        },
        //获取时间
        getTime: function() {
            var date = new Date();
            var seperator1 = "-";
            var seperator2 = ":";
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            var strHour = date.getHours();
            var strMinute = date.getMinutes();
            var strSecond = date.getSeconds();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            if (strHour >= 0 && strHour <= 9) {
                strHour = "0" + strHour;
            }
            if (strMinute >= 0 && strMinute <= 9) {
                strMinute = "0" + strMinute;
            }
            if (strSecond >= 0 && strSecond <= 9) {
                strSecond = "0" + strSecond;
            }
            var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
                " " + strHour + seperator2 + strMinute;
            return currentdate;
        },
        //选择时间
        choseTime: function() {
            var that = this;
            var picker = new mui.DtPicker();
            picker.show(function(rs) {
                that.dateTime = rs.text;
                picker.dispose();
            })

        },
        //发送消息
        send: function(e) {
            var that = this;
            var usersArr = [];
            var imgsArr = [];
            var _this = e.target;
            $.each(that.chosePeoples, function(i, people) {
                if (!that.chosePeoples) return false;
                usersArr.push(people.id)
            })
            $.each(that.imgList, function(i, imgs) {
                if (!that.imgList) return false;
                imgsArr.push(imgs.src)
            })
            var address = that.locations;
            var operatorUsers = usersArr.join(','); //用户集合
            var note = that.content;
            var imgs = imgsArr.join(','); //图片集合
            var dateTime = that.dateTime; //图片集合
            if(!address) {
                mui.toast('事件地点不能为空')
                return false;
            }
            if(!note&&!imgs) {
                mui.toast('描述内容和照片不能同时为空')
                return false;
            }
//            if(!imgs) {
//                mui.toast('照片不能为空')
//                return false;
//            }
            mui(_this).button('loading');
            $.post('/addEvent', {
                "pid": that.pid,
                "operatorUsers": operatorUsers,
                "address": address,
                "note": note,
                "imgs": imgs,
                "eventDate": dateTime,
                lng:that.lng,
                lat:that.lat
            }, function(res) {
                if(res == '保存成功！') {
                    //保存成功
                    console.log(res)
                    mui.toast('保存成功');
                    setTimeout(function() {
                        location.href = "eventReporting.html"
                    }, 1500)
                } else {
                    mui.toast('保存失败');
                }
            })
        }
    }
})
